package com.example.sprintboot.security;

import com.example.sprintboot.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtUtils jwtUtils;
    private final UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            String requestURI = request.getRequestURI();
            logger.info("处理请求: " + requestURI + " [" + request.getMethod() + "]");
            
            // 从请求头获取JWT
            String jwt = parseJwt(request);
            if (jwt != null) {
                logger.info("收到JWT Token");
                
                if (jwtUtils.validateToken(jwt)) {
                    // 解析用户名
                    String username = jwtUtils.getUsernameFromToken(jwt);
                    logger.info("JWT验证成功，用户名: " + username);
                    
                    // 加载用户详情
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    // 设置到安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    logger.info("认证上下文设置成功，用户: " + username + "，权限: " + userDetails.getAuthorities());
                } else {
                    // JWT存在但无效，清除认证上下文
                    SecurityContextHolder.clearContext();
                    logger.warn("无效的JWT Token");
                }
            } else {
                logger.debug("请求中未包含JWT Token");
            }
        } catch (Exception e) {
            // 清除认证上下文
            SecurityContextHolder.clearContext();
            logger.error("JWT认证失败", e);
        }
        filterChain.doFilter(request, response);
    }

    private String parseJwt(HttpServletRequest request) {
        String headerAuth = request.getHeader("Authorization");
        if (headerAuth != null && headerAuth.startsWith("Bearer ")) {
            return headerAuth.substring(7);
        }
        return null;
    }
}